package com.example.test;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NavUtils;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.AMapCameraInfo;
import com.amap.api.maps.model.BitmapDescriptorCreator;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Text;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.autonavi.base.amap.mapcore.Convert;

import java.io.IOException;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements LocationSource{
        //请求权限码
        private static final int REQUEST_PERMISSIONS = 9527;
        private AMapLocationClient mLocationClient = null;
        public AMapLocationClientOption mLocationOption = null;
        private OnLocationChangedListener mListener;
        private ImageButton ibLocation;
        private MapView mapView;
        private TextView mTvLatitude,mTvLongitude,mTvNowLoc;
        private AMap aMap;
        double markerLongitude = 101.742859, markerLatitude = 36.639373; //坐标为青海师范大学城西校区
        private boolean isFirstLoc = true;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ServiceSettings.updatePrivacyShow(this,true,true);
            ServiceSettings.updatePrivacyAgree(this,true);

            mTvLongitude = findViewById(R.id.tv_jd);
            mTvLatitude = findViewById(R.id.tv_wd);
            mTvNowLoc = findViewById(R.id.tv_loc);
            ibLocation = findViewById(R.id.im_button);
            try {
                initMap(savedInstanceState);
            } catch (AMapException e) {
                e.printStackTrace();
            }
            initLocation();
            checkingAndroidVersion();
        }
        /**
         * 初始化定位
         */
        private void initLocation() {
            try{
                //初始化定位
                mLocationClient = new AMapLocationClient(MainActivity.this.getApplicationContext());
                //设置定位回调监听
                myMapListener listener = new myMapListener();
                mLocationClient.setLocationListener(listener);
                //初始化AMapLocationClientOption对象
                mLocationOption = new AMapLocationClientOption();
                //设置定位模式为AMapLocationMode.High_Accuracy，高精度模式。
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                //获取最近3s内精度最高的一次定位结果：
                //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
                mLocationOption.setOnceLocationLatest(true);
                //设置是否返回地址信息（默认返回地址信息）
                mLocationOption.setNeedAddress(true);
                //设置定位请求超时时间，单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
                mLocationOption.setHttpTimeOut(30000);
                //关闭缓存机制，高精度定位会产生缓存。
                mLocationOption.setLocationCacheEnable(false);
                //给定位客户端对象设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
            }catch (Exception e){
                e.printStackTrace();
            }

        }

        /* 初始化地图 */
        private void initMap(Bundle savedInstanceState) throws AMapException {
            mapView = findViewById(R.id.gd_map);
            //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
            mapView.onCreate(savedInstanceState);
            //初始化地图控制器对象
            aMap = mapView.getMap();
            aMap.getUiSettings().setCompassEnabled(true);
            // 设置定位监听
            aMap.setLocationSource(this);
            // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(true);
        }

        @Override
        public void activate(OnLocationChangedListener onLocationChangedListener) {
            mListener = onLocationChangedListener;
            if(mListener == null){
                mLocationClient.startLocation();
            }
        }

        @Override
        public void deactivate() {
            mListener = null;
            if(mLocationClient != null){
                mLocationClient.stopLocation();
            }
        }

        public void resetLocation(View view){
            markerLatitude = 0;
            ibLocation.setVisibility(View.GONE);
        }

        class myMapListener implements AMapLocationListener {
            @SuppressLint("SetTextI18n")
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        double resultLatitude;
                        double resultLongitude;
                        if (markerLatitude == 0) {     //自动定位
                            resultLatitude = aMapLocation.getLatitude();
                            resultLongitude = aMapLocation.getLongitude();
                            ibLocation.setVisibility(View.GONE);
                        }else {    //标点定位
                            resultLatitude = markerLatitude;
                            resultLongitude = markerLongitude;
                            ibLocation.setVisibility(View.VISIBLE);
                        }
                        if(isFirstLoc){
                            mTvLongitude.setText(resultLongitude + "");
                            mTvLatitude.setText(resultLatitude+"");

                            if(mListener != null) {
                                CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(
                                        new CameraPosition(new LatLng(resultLatitude,resultLongitude),18,30,0));
                                aMap.animateCamera(cameraUpdate);

                                mListener.onLocationChanged(aMapLocation);
                            }
                            isFirstLoc = false;
                        }
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AMapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        }


        private void checkingAndroidVersion() {
            //Android6.0及以上先获取权限再定位
            requestPermission();
        }
        /**
         * 动态请求权限
         */
        @AfterPermissionGranted(REQUEST_PERMISSIONS)
        private void requestPermission() {
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
            if (EasyPermissions.hasPermissions(this, permissions)) {
                //true 有权限 开始定位
                Toast.makeText(this,"已获取权限",Toast.LENGTH_LONG).show();
                mLocationClient.startLocation();
            } else {
                //false 无权限
                EasyPermissions.requestPermissions(this, "需要权限", REQUEST_PERMISSIONS, permissions);
            }
        }
        /**
         * 请求权限结果
         */
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            //设置权限请求结果
            EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        }
        @Override
        protected void onResume() {
            super.onResume();
            mapView.onResume();
        }

        @Override
        protected void onPause() {
            super.onPause();
            mapView.onPause();
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            mapView.onDestroy();
            mLocationClient.onDestroy();
            mLocationClient = null;
            mapView = null;
        }
}